using System;
using System.Collections.Generic;
using UnityEngine;
using QFramework;
using Random = UnityEngine.Random;

namespace XCZProject
{
	/// <summary>
	/// 守卫剑技能，控制守卫剑的旋转，碰撞等
	/// </summary>
	public partial class RotateSword : ViewController
	{
		private List<Collider2D> mSwords = new List<Collider2D>();
		
		//public BindableProperty<bool> SuperRotateSword = new BindableProperty<bool>(true);
		
		void Start()
		{
			// Code Here
			Sword.Hide();

			// 当守卫剑数量或者升级飞行物数量改变时触发
			Global.RotateSwordCount.Or(Global.SimpleFlyCount).Register(() =>
			{
				CreateSwords();
			}).UnRegisterWhenGameObjectDestroyed(gameObject);

			Global.RotateSwordRange.RegisterWithInitValue(range =>
			{
				UpdateCirclePos();
			}).UnRegisterWhenGameObjectDestroyed(gameObject);
			
			CreateSwords();
		}

		void CreateSwords()
		{
			// 计算需要生成新剑的数量
			var toAddCount = Global.RotateSwordCount.Value+Global.SimpleFlyCount.Value-mSwords.Count;//计算需要生成新剑的数量

			for (int i = 0; i < toAddCount; i++)
			{
				CreateSword();
			}
			UpdateCirclePos();
		}

		void CreateSword()
		{
			mSwords.Add(Sword.InstantiateWithParent(this)
				.Self(self =>
				{
					// 每次生成新剑的时候，都要给新剑注册碰撞事件
					self.OnTriggerEnter2DEvent(collider =>
					{
						var hurtBox = collider.GetComponent<HurtBox>();
						if (hurtBox)
						{
							if (hurtBox.Owner.CompareTag("Enemy"))
							{
								//hurtBox.Owner.GetComponent<IEnemy>().Hurt(Global.RotateSwordDamage.Value);
								var damageTimes = Global.SuperRotateSword.Value ? Random.Range(2,3+1) : 1;
								DamageSystem.CalculateDamage(Global.RotateSwordDamage.Value*damageTimes,
									hurtBox.Owner.GetComponent<IEnemy>());
										
								// 有一定概率触发击退效果
								if (Random.Range(0,1.0f)<0.5f)
								{
									// 把敌人的距离设置为击退一定距离的方向
									collider.attachedRigidbody.velocity =
										collider.NormalizedDirection2DFrom(self) * 5 +
										collider.NormalizedDirection2DFrom(Player.Default) * 10;
								}
							}
						}
					}).UnRegisterWhenGameObjectDestroyed(self);
				})
				.Show()
			);
		}

		private void Update()
		{
			var speed = Global.SuperRotateSword.Value
				? Time.frameCount * 10
				: Global.RotateSwordSpeed.Value * Time.frameCount;
			
			//var degree = Time.frameCount*Global.RotateSwordSpeed.Value;
			this.LocalEulerAnglesZ(-speed);
		}

		/// <summary>
		/// 更新剑的位置
		/// </summary>
		private void UpdateCirclePos()
		{
			if (mSwords.Count<=0)
			{
				return;
			}
			var radius = Global.RotateSwordRange.Value;//旋转半径

			var durationDegress = 360 / mSwords.Count;//计算剑生成的角度

			for (int i = 0; i < mSwords.Count; i++)
			{
				// 计算剑的位置
				var circleLocalPos = new Vector2(Mathf.Cos(durationDegress*i*Mathf.Deg2Rad), 
					Mathf.Sin(durationDegress*i*Mathf.Deg2Rad)) * radius;
				// 设置剑的位置和角度
				mSwords[i].LocalPosition(circleLocalPos.x, circleLocalPos.y)
					.LocalEulerAnglesZ( durationDegress*i- 90);
			}
		}
	}
}
